package com.lmb.service.impl;

import com.lmb.annotation.LogMethod;
import com.lmb.bean.Reset;
import com.lmb.bean.UserLogin;
import com.lmb.mapper.UserLoginDao;
import com.lmb.service.UserLoginService;
import com.lmb.util.Page;
import com.lmb.util.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserLoginServiceImpl implements UserLoginService {
    public static void main(String[] args) {

    }
    @Autowired
    UserLoginDao userLoginDao;
    @Override
    @LogMethod(serviceName = "用户信息新增",recordReturn = true )//方法执行后记录日志
    public UserLogin add(UserLogin userLogin) {

        userLoginDao.add(userLogin);//新增数据保存成功
        UserLogin result=userLoginDao.one(userLogin.getUser_id());//通过主键查询数据库在的数据
        return result;
    }
    @CacheEvict(value = "userLogin", key = "#p0",allEntries = true)//删除缓存,allEntries = true表示删除所有缓存
    @Override
    @LogMethod(serviceName = "删除用户信息",recordReturn = true)//方法执行后记录日志
    public int del(Integer id) {
        return userLoginDao.del(id);
    }

    @CachePut(value = "userLogin", key = "#p0")//修改缓存
    @Override
    @LogMethod(serviceName = "用户信息处理")//方法执行后记录日志
    public UserLogin edit(UserLogin userLogin) {
        userLoginDao.edit(userLogin);
        UserLogin result=userLoginDao.one(userLogin.getUser_id());
        return result;
    }

    @Override
    public List<UserLogin> all(UserLogin userLogin) {
        return userLoginDao.all(userLogin);
    }
    @Cacheable(value = "userLogin", key = "#p0")//
    @Override
    public UserLogin one(Integer id) {
        return userLoginDao.one(id);
    }

    @Override
    public void page(Page page, UserLogin userLogin) {
        int count = userLoginDao.pageCount(userLogin);
        Object data = userLoginDao.page(page, userLogin);
        page.setCount(count);
        page.setData(data);
    }

    @Override
    public UserLogin reset(String old_password, String new_password, Integer user_id) {
        if (user_id==null){
            throw new RuntimeException("用户未登录");
        }
        if(!PasswordUtil.checkPassword(old_password,userLoginDao.one(user_id).getUser_password())){
            throw new RuntimeException("原密码错误");
        }
        UserLogin user=userLoginDao.one(user_id);
        user.setUser_password(PasswordUtil.getEncryption(new_password));
        userLoginDao.edit(user);
        return user;
    }

}
